package com.xing.user.exception;

import com.liu.common.exception.RRException;
import com.liu.common.utils.R;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.HttpStatus;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ResponseStatus;

import java.util.List;

/**
* @description 全局异常处理器
*/
@ControllerAdvice
public class GlobalExceptionHandler {
    private static final Logger log = LoggerFactory.getLogger(GlobalExceptionHandler.class);

    @ResponseBody
    @ExceptionHandler(RRException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR) // 该异常枚举错误码为500，
    public R customException(RRException exception) {
        log.error("内部异常：{}", exception.getMessage());
        return R.error(exception.getCode(),exception.getMessage());
    }

    @ResponseBody
    @ExceptionHandler(Exception.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R exception(Exception exception) {
        log.error("系统异常：{}", exception.getMessage());
        if(exception.getMessage().equals("不允许访问")){
            return R.error("没有操作此功能的权限");
        }
        return R.error(exception.getMessage());
    }
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    @ResponseStatus(HttpStatus.INTERNAL_SERVER_ERROR)
    public R doMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        // 可能有多个参数错误 一并返回
        BindingResult bindingResult = e.getBindingResult();
        // 获取参数错误集合
        List<FieldError> fieldErrors = bindingResult.getFieldErrors();
        // 遍历获取错误描述信息
        StringBuilder sb = new StringBuilder();
        fieldErrors.forEach(fieldError -> {
            sb.append(fieldError.getDefaultMessage()).append(",");});
        // 日志记录
        log.error("参数错误：{}", sb.toString());
        // 返回错误信息
        return R.error(sb.toString());
    }
}